package com.shiyi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shiyi.service.RedisService;
import com.shiyi.vo.*;
import com.shiyi.common.*;
import com.shiyi.entity.*;
import com.shiyi.enums.SearchModelEnum;
import com.shiyi.enums.YesOrNoEnum;
import com.shiyi.exception.BusinessException;
import com.shiyi.mapper.*;
import com.shiyi.service.ArticleService;
import com.shiyi.service.SystemConfigService;
import com.shiyi.strategy.context.SearchStrategyContext;
import com.shiyi.util.*;
import com.shiyi.dto.ArticleDTO;
import com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter;
import com.vladsch.flexmark.util.data.MutableDataSet;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.shiyi.common.Constants.*;
import static com.shiyi.common.RedisConstants.*;
import static com.shiyi.common.ResultCode.*;
import static com.shiyi.enums.PublishEnum.PUBLISH;

/**
 * <p>
 * 博客文章表 服务实现类
 * </p>
 *
 * @author blue
 * @since 2021-08-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, BlogArticle> implements ArticleService {

    private final CategoryMapper categoryMapper;

    private final SystemConfigService systemConfigService;

    private final RedisService redisService;

    private final TagsMapper tagsMapper;

    private final CommentMapper commentMapper;

    private final SearchStrategyContext searchStrategyContext;

    private final RestTemplate restTemplate;

    private final HttpServletRequest request;

    private final ElasticsearchUtil elasticsearchUtil;

    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Value("${baidu.url}")
    private String baiduUrl;


    /**
     *  后台获取所有文章
     * @return
     */
    @Override
    public ResponseResult listArticle(Map<String,Object> map) {
        Page<ArticleListVO> data = baseMapper.selectArticle(new Page<>((Integer)map.get("pageNo"), (Integer)map.get("pageSize")),map);
        return ResponseResult.success(data);
    }

    /**
     *  后台获取文章详情
     * @return
     */
    @Override
    public ResponseResult getArticleById(Long id) {
        ArticleDTO articleDTO = baseMapper.selectPrimaryKey(id);
        articleDTO.setTags(tagsMapper.selectByArticleId(id));
        return ResponseResult.success(articleDTO);
    }

    /**
     *  添加文章
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult insertArticle(ArticleDTO article) {
        BlogArticle blogArticle = BeanCopyUtils.copyObject(article, BlogArticle.class);
        blogArticle.setUserId(StpUtil.getLoginIdAsLong());
        //添加分类
        Long categoryId = savaCategory(article.getCategoryName());
        //添加标签
        List<Long> tagList = getTagsList(article);

        blogArticle.setCategoryId(categoryId);

        int insert = baseMapper.insert(blogArticle);
        if (insert > 0) {
            tagsMapper.saveArticleTags(blogArticle.getId(),tagList);
        }
        return ResponseResult.success();
    }

    /**
     *  修改文章
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateArticle(ArticleDTO article) {
        BlogArticle blogArticle = baseMapper.selectById(article.getId());
        Assert.notNull(blogArticle,ARTICLE_NOT_EXIST.getDesc());

        //添加分类
        Long categoryId = savaCategory(article.getCategoryName());
        //添加标签
        List<Long> tagList = getTagsList(article);

        blogArticle = BeanCopyUtils.copyObject(article, BlogArticle.class);
        blogArticle.setCategoryId(categoryId);
        blogArticle.setUserId(StpUtil.getLoginIdAsLong());
        baseMapper.updateById(blogArticle);

        //先删出所有标签
        tagsMapper.deleteByArticleIds(Collections.singletonList(blogArticle.getId()));
        //然后新增标签
        tagsMapper.saveArticleTags(blogArticle.getId(),tagList);

        return ResponseResult.success();
    }

    /**
     *  删除文章
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteArticle(Long id) {
        int row = baseMapper.deleteById(id);
        if (row > 0) {
            this.deleteAfter(Collections.singletonList(id));
        }
        return ResponseResult.success();
    }

    /**
     * 批量删除文章
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteBatchArticle(List<Long> ids) {
        int rows = baseMapper.deleteBatchIds(ids);
        if (rows > 0) {
            this.deleteAfter(ids);
        }
        return ResponseResult.success();
    }

    /**
     *  置顶文章
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult putTopArticle(ArticleDTO article) {
        baseMapper.putTopArticle(article);
        return ResponseResult.success();
    }


    /**
     *  文章百度推送
     * @return
     */
    @Override
    public ResponseResult articleSeo(List<Long> ids) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("Host", "data.zz.baidu.com");
        headers.add("User-Agent", "curl/7.12.1");
        headers.add("Content-Length", "83");
        headers.add("Content-Type", "text/plain");

        ids.forEach(item -> {
            String url = "https://www.88688.team/article/" + item;
            HttpEntity<String> entity = new HttpEntity<>(url, headers);
            restTemplate.postForObject(baiduUrl, entity, String.class);
        });
        return ResponseResult.success();
    }

    /**
     *  抓取文章
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult reptile(String url) {
        try {
            Document document = Jsoup.connect(url).get();
            Elements title  = document.getElementsByClass("title-article");
            Elements tags  = document.getElementsByClass("tag-link");
            Elements content  = document.getElementsByClass("article_content");
            Assert.isTrue(StringUtils.isNotBlank(content.toString()),CRAWLING_ARTICLE_FAILED.getDesc());

            //爬取的是HTML内容，需要转成MD格式的内容
            String newContent = content.get(0).toString().replaceAll("<code>", "<code class=\"lang-java\">");
            MutableDataSet options = new MutableDataSet();
            String markdown = FlexmarkHtmlConverter.builder(options).build().convert(newContent)
                    .replace("lang-java","java");

            //文章封面图片 由https://api.btstu.cn/该网站随机获取
            //注释时间 2022年12月29日20:07:04  因为接口不能用了
           /* String strResult = restTemplate.getForObject(IMG_URL_API_BT, String.class);
            JSONObject jsonObject = JSON.parseObject(strResult);
            Object imgUrl = jsonObject.get("imgurl");*/

            //从七牛云中生成随机数
            String imgUrl = randomImgByQiNiuYun().getData().toString();
            BlogArticle entity = BlogArticle.builder().userId(7L).contentMd(markdown)
                    .categoryId(OTHER_CATEGORY_ID).isOriginal(YesOrNoEnum.YES.getCode()).originalUrl(url)
                    .title(title.get(0).text()).avatar(imgUrl.toString()).content(newContent).build();

            baseMapper.insert(entity);
            //为该文章添加标签
            List<Long> tagsId = new ArrayList<>();
            tags.forEach(item ->{
                String tag = item.text();
                Tags result = tagsMapper.selectOne(new QueryWrapper<Tags>().eq(SqlConf.NAME,tag ));
                if (result == null){
                    result = Tags.builder().name(tag).build();
                    tagsMapper.insert(result);
                }
                tagsId.add(result.getId());
            });
            tagsMapper.saveArticleTags(entity.getId(),tagsId);

            log.info("文章抓取成功，内容为:{}", JSON.toJSONString(entity));
        } catch (IOException e) {
            throw new BusinessException(e);
        }
        return ResponseResult.success();
    }

    /**
     *  发布或下架文章
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult publishAndShelf(ArticleDTO article) {
        baseMapper.publishAndShelf(article);
        return ResponseResult.success();
    }

    /**
     * 随机获取文章封面
     * @return
     */
    @Override
    public ResponseResult randomImg() {
        //文章封面图片 由https://api.btstu.cn/该网站随机获取
        String result = restTemplate.getForObject(IMG_URL_API_BT, String.class);
        Object imgUrl = JSON.parseObject(result).get("imgurl");
        return ResponseResult.success(imgUrl);
    }

    /**
     * 从七牛云中随机取出一张图片作为封面
     * @return
     */
    @Override
    public ResponseResult randomImgByQiNiuYun() {
        //先来个随机数 （1-52的随机数）
        int max = 166, min = 1;
        int random = (int) (Math.random() * (max - min) + min);
        String imgUrl = QNY_IMG_URL + "/fengmian/"+"fm" + random + ".jpg";
        return ResponseResult.success(imgUrl);
    }


    /**
     * 获取每日新闻，添加到文章里面
     * @param
     * @return
     */
    @Override
    public ResponseResult getDaysNews() {
        String path = "bulletin/index";
        //从缓存中获取微信群名
        Object redisObject = redisService.getCacheObject("wechat-webconfig");
        //需要发送的群组名
        String [] groups ={};
        //智能微秘书的key
        String wei_mi_shu_key = "";
        //天行数据的key
        String tx_key = "";
        if(redisObject!=null){
            //缓存中有数据
            JSONObject jsonObject = (JSONObject) redisObject;
            String groupChats = jsonObject.getString("groupChats");
            wei_mi_shu_key = jsonObject.getString("znwms");
            //天行数据的key
            tx_key = jsonObject.getString("txkey");
            //拿到要发送群的数组
            groups = groupChats.split(",");
        }

        //调用每日简报的接口
        String body = HttpUtil
                .createGet(TIAN_XING_API + path + "?key=" + tx_key)
                .execute()
                .body();
        /*String body = "{\n" +
                "  \"code\": 200,\n" +
                "  \"msg\": \"success\",\n" +
                "  \"result\": {\n" +
                "    \"list\": [\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 11:32:03\",\n" +
                "        \"title\": \"上海全面推广人工智能精准医学检验 AI+医疗造福患者\",\n" +
                "        \"digest\": \"中国信息通信研究院院长余晓晖指出，发展智能医疗应进一步完善技术创新体系，建设一批面向行业的创新中心、重点实验室等创新载体，打造合作机制。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 10:35:07\",\n" +
                "        \"title\": \"国务院联防联控机制综合组：部署落实新十条防控措施 加快推进医疗资源准备工作\",\n" +
                "        \"digest\": \"会议指出，随着新冠病毒变异和全球疫情变化，以习近平同志为核心的党中央坚持走小步不停步，先后审议出台二十条、新十条措施，推动我国疫情防控进入新阶段。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 09:56:09\",\n" +
                "        \"title\": \"降阶，缩短时间！欧洲心脏病学会老年抗栓共识\",\n" +
                "        \"digest\": \"共识指出，对于老年人来说，选择最佳抗栓治疗方案虽然具有挑战性，但可根据个体特征和多种治疗方案而制定。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 09:21:54\",\n" +
                "        \"title\": \"国家卫健委：昨日新增本土3034+10551| 全国疫情最新消息（2022.12.10）\",\n" +
                "        \"digest\": \"31个省（自治区、直辖市）和新疆生产建设兵团报告新增无症状感染者10729例，其中境外输入178例。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 08:54:26\",\n" +
                "        \"title\": \"广东新增本土确诊病例1115例 新增本土无症状感染者1819例\",\n" +
                "        \"digest\": \"12月9日0-24时，广东省新增本土确诊病例993例，新增本土无症状感染者1819例，另有122例本土无症状感染者转确诊病例。（广东省卫健委网站）\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 08:50:46\",\n" +
                "        \"title\": \"12月9日北京新增924例本土确诊病例和1308例无症状感染者\",\n" +
                "        \"digest\": \"12月9日0时至24时，北京新增924例本土确诊病例和1308例无症状感染者(含9例无症状感染者转确诊病例)，无新增疑似病例。（北京市卫生健康委员会）\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 22:53:38\",\n" +
                "        \"title\": \"钟南山：新冠产生的症状会慢慢消失，我们不叫它后遗症\",\n" +
                "        \"digest\": \"钟南山：“医学上对于后遗症有严格的定义，指的是疾病造成的损害终身存在。一些新冠产生的症状会慢慢消失，我们不叫它后遗症。我目前还没看到特别明显的对器官引起长期功能不全的案例。”\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 22:24:27\",\n" +
                "        \"title\": \"用新冠病毒治疗癌症？研究发现新冠刺突蛋白能抑制肺癌发展\",\n" +
                "        \"digest\": \"研究结果突出了重组SARS-CoV-2刺突S1蛋白晚期肺癌患者的新治疗途径。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 21:31:47\",\n" +
                "        \"title\": \"所有医疗机构都要接诊阳性患者！院感防控该怎么做？\",\n" +
                "        \"digest\": \"无论是从卫生经济学的角度，还是从医务人员疲倦心理的角度来说，防控的要求必然会放松。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 20:48:11\",\n" +
                "        \"title\": \"我国重症救治能力如何？全国重症床位近每10万人10张\",\n" +
                "        \"digest\": \"我国重症救治能力如何？国家卫健委医政司司长焦雅辉回应：目前，全国重症医学床位总数是13.81万张，其中三级医疗机构的重症医学床位是10.65万张，重症医学床位接近十万人十张的水平。重症医学的医师总数是8.05万人，还有可转换ICU的储备的医师有10.6万人。另外，重症专业的护士是22万人，可以转换ICU的护士是17.77万人。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 20:21:10\",\n" +
                "        \"title\": \"如何应对可能出现的感染高峰？陈尔真：门急诊做好“三分”管理\",\n" +
                "        \"digest\": \"连日来，国家和地方持续优化新冠防控措施，随着人员交流增多，人群感染风险可能增加。那么，各大医院准备情况如何？当前形势下，大众又该如何合理就医？\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 19:49:33\",\n" +
                "        \"title\": \"村室每月1000元！一地发布标准\",\n" +
                "        \"digest\": \"切实提高乡村医生收入，保障乡村医生待遇。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 19:47:53\",\n" +
                "        \"title\": \"网传海宁某医院医生涉及买卖器官， 当地辟谣\",\n" +
                "        \"digest\": \"网传海宁市某医院医生涉及人体器官买卖。经核实，海宁市人民医院肾内科主任金雯佳涉嫌严重违法，主动投案，目前正在接受海宁市监委监察调查，不存在买卖器官的情况。请广大网友切勿轻信、转发、传播谣言。（海宁新闻网）\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 18:53:50\",\n" +
                "        \"title\": \"实行学术造假“一票否决制”！四川省深化卫生专业技术人员职称制度改革实施方案\",\n" +
                "        \"digest\": \"对于临床医师，将门诊工作时间、收治患者数量、手术数量等作为申报条件。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 17:39:35\",\n" +
                "        \"title\": \"首届上海合作组织国际和平妇幼健康发展论坛在上海举办\",\n" +
                "        \"digest\": \"9日，首届上海合作组织国际和平妇幼健康发展论坛举行，以“交流、互鉴、合作、发展”为主题，围绕“儿童优先、母亲安全”的国际共识，推进上合组织各方在妇幼健康与儿童早期发展领域深化合作。开幕式上，中方发布《中方关于促进上海合作组织妇幼健康合作的倡议（上海）》，提出开展妇幼健康治理策略互鉴、加强妇幼健康医疗技术交流、开展妇女儿童重大健康问题研究合作、搭建妇幼健康产业联盟、建立妇幼健康帮扶基金等五项倡议。\"\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}";*/


        JSONObject jsonObjectResult = JSON.parseObject(body);
        Integer code = jsonObjectResult.getInteger("code");
        if(code!=200){
            log.error("请求每日新闻的接口出错，出错信息："+body);
            return ResponseResult.error();
        }
        log.error("请求每日新闻的接口成功："+body);
        JSONObject resultObject = jsonObjectResult.getJSONObject("result");
        //获取新闻列表
        JSONArray contentList = resultObject.getJSONArray("list");
        //获取文章的封面信息
       /* String strResult = restTemplate.getForObject(IMG_URL_API_BT, String.class);
        JSONObject jsonObject = JSON.parseObject(strResult);
        Object imgUrl = jsonObject.get("imgurl");*/


        //从七牛云中生成随机数
        String imgUrl = randomImgByQiNiuYun().getData().toString();
        //将新闻列表封装成markdown文章
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String todayDate = simpleDateFormat.format(new Date());
        String titleContent = "# "+todayDate+"新闻简要<br/>";
        StringBuilder stringBuilder = new StringBuilder(titleContent);
        //发送到微信群里面的信息
        JSONObject contentObject = new JSONObject();
        contentObject.put("todayDate",todayDate);
        JSONArray array = new JSONArray();

        //遍历接口返回来的json数据
        contentList.forEach(item->{
            JSONObject arrayObject = new JSONObject();
            JSONObject itemObject = (JSONObject)item;
            stringBuilder.append("⏱️");
            stringBuilder.append(itemObject.getString("mtime"));
            stringBuilder.append("<br/>");
            stringBuilder.append("### ");
            stringBuilder.append("🏷️");
            stringBuilder.append(itemObject.getString("title"));
            stringBuilder.append("<br/>");
            stringBuilder.append("📃");
            stringBuilder.append(itemObject.getString("digest"));
            stringBuilder.append("<br/>");
            stringBuilder.append("<br/>");
            stringBuilder.append("---");
            stringBuilder.append("<br/>");
            //标题
            arrayObject.put("title",itemObject.getString("title"));
            //内容
            arrayObject.put("digest",itemObject.getString("digest"));
            //时间
            arrayObject.put("mtime",itemObject.getString("mtime"));
            array.add(arrayObject);
        });
        contentObject.put("list",array);
        stringBuilder.append("(本文所有数据均来自天行数据api，如有侵权，联系即删~)");
        //将拿到的内容放在Markdown中
        String newContent = stringBuilder.toString();
        MutableDataSet options = new MutableDataSet();
        String markdown = FlexmarkHtmlConverter
                .builder(options)
                .build()
                .convert(newContent)
                .replace("lang-java","java");
        //构建文章的实体
        BlogArticle entity = BlogArticle.builder()
                .userId(7L)
                .contentMd(markdown)
                .categoryId(DAYYS_NEWS)
                .isOriginal(YesOrNoEnum.NO.getCode())
                //转载地址
                .originalUrl("https://www.tianapi.com/")
                .isPublish(1)
                .keywords("每日新闻,穆雄雄,新闻简报,早安")
                .title(todayDate+"新闻简要")
                .avatar(imgUrl)
                .content(newContent)
                .build();
        baseMapper.insert(entity);
        //添加标签
        tagsMapper.saveArticleTags(entity.getId(),new ArrayList<Long>() {{add(63L);}});
        log.info("每日新闻添加到文章成功："+ JSON.toJSONString(entity));
        contentObject.put("aid",entity.getId());
        //调用推送到微信的方法
        sendWechat(contentObject);
        return ResponseResult.success("发送成功");
    }

    /**
     * 获取历史上的今天内容
     * @return
     */
    @Override
    public ResponseResult getTodayInHistory() {
        String path = "lishi/index";
        //获取今天的日期
        SimpleDateFormat format  = new SimpleDateFormat("MMdd");
        String newDate = format.format(new Date());
        //从缓存中获取微信群名
        Object redisObject = redisService.getCacheObject("wechat-webconfig");
        //需要发送的群组名
        String [] groups ={};
        //智能微秘书的key
        String wei_mi_shu_key = "";
        //天行数据的key
        String tx_key = "";
        if(redisObject!=null){
            //缓存中有数据
            JSONObject jsonObject = (JSONObject) redisObject;
            String groupChats = jsonObject.getString("groupChats");
            wei_mi_shu_key = jsonObject.getString("znwms");
            //天行数据的key
            tx_key = jsonObject.getString("txkey");
            //拿到要发送群的数组
            groups = groupChats.split(",");
        }

        //调用每日简报的接口
        String body = HttpUtil
                .createGet(TIAN_XING_API + path + "?key=" + tx_key+"&date="+newDate)
                .execute()
                .body();
       /* String body = "{\n" +
                "  \"code\": 200,\n" +
                "  \"msg\": \"success\",\n" +
                "  \"result\": {\n" +
                "    \"list\": [\n" +
                "      {\n" +
                "        \"title\": \"俄国作家陀思妥耶夫斯基逝世\",\n" +
                "        \"lsdate\": \"1881-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"世界网球赛戴维斯杯产生\",\n" +
                "        \"lsdate\": \"1900-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"中国足球队首次出国比赛\",\n" +
                "        \"lsdate\": \"1916-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"首次开创巴黎飞往伦敦的商业性飞行\",\n" +
                "        \"lsdate\": \"1919-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"上海日资纱厂工人举行大罢工\",\n" +
                "        \"lsdate\": \"1925-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"夏明翰烈士就义\",\n" +
                "        \"lsdate\": \"1928-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"共产国际对中共作出新指示\",\n" +
                "        \"lsdate\": \"1928-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"上海发生“二·九”血案\",\n" +
                "        \"lsdate\": \"1947-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"中国民盟主席张澜逝世\",\n" +
                "        \"lsdate\": \"1955-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"龙梅和玉荣战胜暴风雪保护羊群\",\n" +
                "        \"lsdate\": \"1964-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"中国政府表示尽一切力量援越抗美\",\n" +
                "        \"lsdate\": \"1965-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"北京烤鸭店恢复“全聚德”老字号\",\n" +
                "        \"lsdate\": \"1980-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"我国第一座大型高通量原子反应堆建成\",\n" +
                "        \"lsdate\": \"1981-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"雅鲁泽尔斯基将军接任波兰总理\",\n" +
                "        \"lsdate\": \"1981-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"中央要求做好计划生育工作\",\n" +
                "        \"lsdate\": \"1982-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"苏共中央总书记安德罗波夫逝世\",\n" +
                "        \"lsdate\": \"1984-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"法国探险家德拉日完成横渡大西洋的壮举\",\n" +
                "        \"lsdate\": \"1995-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"我国转基因羊研究获重大突破\",\n" +
                "        \"lsdate\": \"1998-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"首届“鲁迅文学奖”评选揭晓\",\n" +
                "        \"lsdate\": \"1998-02-09\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"title\": \"谢瓦尔德纳泽险遭炸弹袭击\",\n" +
                "        \"lsdate\": \"1998-02-09\"\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}";*/

        JSONObject jsonObjectResult = JSON.parseObject(body);
        Integer code = jsonObjectResult.getInteger("code");
        if(code!=200){
            log.error("请求历史上今天的接口出错，出错信息："+body);
            return ResponseResult.error();
        }
        log.error("请求历史上今天的接口成功："+body);
        JSONObject resultObject = jsonObjectResult.getJSONObject("result");
        //获取新闻列表
        JSONArray contentList = resultObject.getJSONArray("list");
        //获取文章的封面信息
       /* String strResult = restTemplate.getForObject(IMG_URL_API_BT, String.class);
        JSONObject jsonObject = JSON.parseObject(strResult);
        Object imgUrl = jsonObject.get("imgurl");*/

        //从七牛云中生成随机数
        String imgUrl = randomImgByQiNiuYun().getData().toString();
        //将新闻列表封装成markdown文章
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String todayDate = simpleDateFormat.format(new Date());
        String titleContent = "# "+todayDate+"历史上的今天<br/>";
        StringBuilder stringBuilder = new StringBuilder(titleContent);
        //发送到微信群里面的信息
        JSONObject contentObject = new JSONObject();
        contentObject.put("todayDate",todayDate);
        JSONArray array = new JSONArray();

        //遍历接口返回来的json数据
        contentList.forEach(item->{
            JSONObject arrayObject = new JSONObject();
            JSONObject itemObject = (JSONObject)item;
            stringBuilder.append("⏱️");
            stringBuilder.append(itemObject.getString("lsdate"));
            stringBuilder.append("<br/>");
            stringBuilder.append("### ");
            stringBuilder.append("🏷️");
            stringBuilder.append(itemObject.getString("title"));
            stringBuilder.append("<br/>");
            stringBuilder.append("<br/>");
            stringBuilder.append("---");
            stringBuilder.append("<br/>");
            //标题
            arrayObject.put("title",itemObject.getString("title"));
            //时间
            arrayObject.put("lsdate",itemObject.getString("lsdate"));
            array.add(arrayObject);
        });
        contentObject.put("list",array);
        stringBuilder.append("(本文所有数据均来自天行数据api，如有侵权，联系即删~)");
        //将拿到的内容放在Markdown中
        String newContent = stringBuilder.toString();
        MutableDataSet options = new MutableDataSet();
        String markdown = FlexmarkHtmlConverter
                .builder(options)
                .build()
                .convert(newContent)
                .replace("lang-java","java");
        //构建文章的实体
        BlogArticle entity = BlogArticle.builder()
                .userId(7L)
                .contentMd(markdown)
                .categoryId(TODAY_HISTOY)
                .isOriginal(YesOrNoEnum.NO.getCode())
                //转载地址
                .originalUrl("https://www.tianapi.com/")
                .isPublish(1)
                .keywords("每日新闻,穆雄雄,新闻简报,早安,历史上的今天")
                .title(todayDate+"历史上的今天")
                .avatar(imgUrl)
                .content(newContent)
                .build();
        baseMapper.insert(entity);
        //添加标签
        tagsMapper.saveArticleTags(entity.getId(),new ArrayList<Long>() {{add(73L);}});
        log.info("历史上的今天添加到文章成功："+ JSON.toJSONString(entity));
        contentObject.put("aid",entity.getId());
        //调用推送到微信的方法
        sendWechatTodayHistoy(contentObject);
        return ResponseResult.success("发送成功");
    }

    /**
     * 将每日社会新闻推送到微信群中
     * @return
     */
    @Override
    public void sendWechat(JSONObject contentObject) {
        String url = WEI_MI_SHU_API + "/openapi/v1/chat/room";
        WeiZhiMiShuVO weiZhiMiShuVO = new WeiZhiMiShuVO();
        weiZhiMiShuVO.setType(1);

        //从缓存中获取微信群名
        Object redisObject = redisService.getCacheObject("wechat-webconfig");
        //需要发送的群组名
        String [] groups ={};
        //智能微秘书的key
        String wei_mi_shu_key = "";
        //天行数据的key
        String tx_key = "";
        if(redisObject!=null){
            //缓存中有数据
            JSONObject jsonObject = (JSONObject) redisObject;
            String groupChats = jsonObject.getString("groupChats");
            wei_mi_shu_key = jsonObject.getString("znwms");
            //天行数据的key
            tx_key = jsonObject.getString("txkey");
            //拿到要发送群的数组
            groups = groupChats.split(",");
        }

        //拿到发送的消息列表
        JSONArray array = contentObject.getJSONArray("list");
        String todayDate = contentObject.getString("todayDate");
        StringBuilder sb = new StringBuilder("今天是：" + todayDate);
        //根据阳历计算农历
        Calendar today = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        // 因为按中国礼拜一作为第一天所以这里减1
        String week = "";
        try {
            week = DateUtils.getDaysByWeekChina(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            today.setTime(DateUtils.chineseDateFormat.parse(todayDate));
            DateUtils lunar = new DateUtils(today);
            String nongli = lunar.toString();
            nongli = nongli.substring(nongli.indexOf("年")+1);
            sb.append("，星期")
                    .append(week)
                    .append("，农历")
                    .append(nongli)
                    .append("，早安~")
                    .append("\n")
            ;

        } catch (ParseException e) {
            e.printStackTrace();
        }
        int index = 1;
        for (Object o : array) {
            JSONObject item = (JSONObject) o;
            //标题加时间
            sb.append("")
                    .append(index)
                    .append(".")
                    .append(item.getString("title"))
                    .append("\n");
            ;
            index++;
        }
        sb.append("详情请点击：https://88688.team/articles/")
                .append(contentObject.getString("aid"))
                .append(" 查看~\n");
        sb.append("【早安寄语】")
                .append(goodMorning(tx_key));
        System.out.println("发送的消息为：" + sb.toString());
        weiZhiMiShuVO.setContent(sb.toString());

//        for (String str : groups) {
        String str = "雄雄的小课堂| 互联网行业交流群①";
            JSONObject object = new JSONObject();
            object.put("apiKey", wei_mi_shu_key);
            object.put("roomName", str);
            object.put("message", weiZhiMiShuVO);
            String body = HttpUtil
                    .createPost(url)
                    .body(JSON.toJSONString(object))
                    .execute()
                    .body()
            ;
            System.out.println("群名："+str+",请求微秘书接口的结果："+body);
//        }

    }

    /**
     * 给微信群发送历史上的今天
     * @param contentObject
     */
    public void sendWechatTodayHistoy(JSONObject contentObject) {
        String url = WEI_MI_SHU_API + "/openapi/v1/chat/room";
        WeiZhiMiShuVO weiZhiMiShuVO = new WeiZhiMiShuVO();
        weiZhiMiShuVO.setType(1);

        //从缓存中获取微信群名
        Object redisObject = redisService.getCacheObject("wechat-webconfig");
        //需要发送的群组名
        String [] groups ={};
        //智能微秘书的key
        String wei_mi_shu_key = "";
        //天行数据的key
        String tx_key = "";
        if(redisObject!=null){
            //缓存中有数据
            JSONObject jsonObject = (JSONObject) redisObject;
            String groupChats = jsonObject.getString("groupChats");
            wei_mi_shu_key = jsonObject.getString("znwms");
            //天行数据的key
            tx_key = jsonObject.getString("txkey");
            //拿到要发送群的数组
            groups = groupChats.split(",");
        }

        //拿到发送的消息列表
        JSONArray array = contentObject.getJSONArray("list");
        String todayDate = contentObject.getString("todayDate");
        StringBuilder sb = new StringBuilder("今天是：" + todayDate);
        //根据阳历计算农历
        Calendar today = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        // 因为按中国礼拜一作为第一天所以这里减1
        String week = "";
        try {
            week = DateUtils.getDaysByWeekChina(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            today.setTime(DateUtils.chineseDateFormat.parse(todayDate));
            DateUtils lunar = new DateUtils(today);
            String nongli = lunar.toString();
            nongli = nongli.substring(nongli.indexOf("年")+1);
            sb.append("，星期")
                    .append(week)
                    .append("，农历")
                    .append(nongli)
                    .append("，历史上的今天发生了什么？")
                    .append("\n")
            ;

        } catch (ParseException e) {
            e.printStackTrace();
        }
        int index = 1;
        for (Object o : array) {
            JSONObject item = (JSONObject) o;
            //标题加时间
            sb.append("")
                    /*.append(index)
                    .append(".")*/
                    .append(item.getString("lsdate"))
                    .append("  ")
                    .append(item.getString("title"))
                    .append("\n");
            ;
            index++;
        }
        sb.append("详情请点击：https://88688.team/articles/")
                .append(contentObject.getString("aid"))
                .append(" 查看~\n");
        sb.append("【早安寄语】")
                .append(goodMorning(tx_key));
                //.append("每天早上一句");
        System.out.println("发送的消息为：" + sb.toString());
        weiZhiMiShuVO.setContent(sb.toString());

        for (String str : groups) {
            JSONObject object = new JSONObject();
            object.put("apiKey", wei_mi_shu_key);
            object.put("roomName", str);
            object.put("message", weiZhiMiShuVO);
            String body = HttpUtil
                    .createPost(url)
                    .body(JSON.toJSONString(object))
                    .execute()
                    .body()
                    ;
            System.out.println("群名："+str+",请求微秘书接口的结果："+body);
        }

    }

    /**
     * 给微信群发送IT新闻
     * @param contentObject
     */
    public void sendWechatITNews(JSONObject contentObject) {
        String url = WEI_MI_SHU_API + "/openapi/v1/chat/room";
        WeiZhiMiShuVO weiZhiMiShuVO = new WeiZhiMiShuVO();
        weiZhiMiShuVO.setType(1);

        //从缓存中获取微信群名
        Object redisObject = redisService.getCacheObject("wechat-webconfig");
        //需要发送的群组名
        String [] groups ={};
        //智能微秘书的key
        String wei_mi_shu_key = "";
        //天行数据的key
        String tx_key = "";
        if(redisObject!=null){
            //缓存中有数据
            JSONObject jsonObject = (JSONObject) redisObject;
            String groupChats = jsonObject.getString("groupChats");
            wei_mi_shu_key = jsonObject.getString("znwms");
            //天行数据的key
            tx_key = jsonObject.getString("txkey");
            //拿到要发送群的数组
            groups = groupChats.split(",");
        }
        //拿到发送的消息列表
        JSONArray array = contentObject.getJSONArray("list");
        String todayDate = contentObject.getString("todayDate");
        StringBuilder sb = new StringBuilder("今天是：" + todayDate);
        //根据阳历计算农历
        Calendar today = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        // 因为按中国礼拜一作为第一天所以这里减1
        String week = "";
        try {
            week = DateUtils.getDaysByWeekChina(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            today.setTime(DateUtils.chineseDateFormat.parse(todayDate));
            DateUtils lunar = new DateUtils(today);
            String nongli = lunar.toString();
            nongli = nongli.substring(nongli.indexOf("年")+1);
            sb.append("，星期")
                    .append(week)
                    .append("，农历")
                    .append(nongli)
                    .append("，早安~")
                    .append("\n")
            ;

        } catch (ParseException e) {
            e.printStackTrace();
        }
        int index = 1;
        for (Object o : array) {
            JSONObject item = (JSONObject) o;
            //标题加时间
            sb.append("")
                    .append(index)
                    .append(".")
                    .append(item.getString("title"))
                    .append("\n");
            ;
            index++;
        }
        sb.append("各新闻详情来源请前往：https://88688.team/articles/")
                .append(contentObject.getString("aid"))
                .append(" 查看~\n");
        sb.append("【早安寄语】")
                .append(goodMorning(tx_key));
        System.out.println("发送的消息为：" + sb.toString());
        weiZhiMiShuVO.setContent(sb.toString());

//        for (String str : groups) {
            JSONObject object = new JSONObject();
            object.put("apiKey", wei_mi_shu_key);
            String str = "雄雄的小课堂技术交流群";
            object.put("roomName", str);
            object.put("message", weiZhiMiShuVO);
            String body = HttpUtil
                    .createPost(url)
                    .body(JSON.toJSONString(object))
                    .execute()
                    .body()
                    ;
            System.out.println("群名："+str+",请求微秘书接口的结果："+body);
//        }


    }

    /**
     * 每天将指定信息推送到微信个人
     */
    @Override
    public void sendWechatToUser() {
        String url = WEI_MI_SHU_API + "/openapi/v1/chat/contact";
        WeiZhiMiShuVO weiZhiMiShuVO = new WeiZhiMiShuVO();
        //发送文字信息
        weiZhiMiShuVO.setType(1);
        try {
            //从缓存中获取微信群名
            Object redisObject = redisService.getCacheObject("wechat-webconfig");
            //需要发送的人
            String [] users = {} ;
            //智能微秘书的key
            String wei_mi_shu_key = "";
            //天行数据的key
            String tx_key = "";
            if(redisObject!=null){
                //缓存中有数据
                JSONObject jsonObject = (JSONObject) redisObject;
                String groupChats = jsonObject.getString("nameChats");
                //智能微秘书的key
                wei_mi_shu_key = jsonObject.getString("znwms");
                //天行数据的key
                tx_key = jsonObject.getString("txkey");
                //拿到要发送群的数组
                users = groupChats.split(",");
            }

            //拿到发送的消息列表
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            SimpleDateFormat format_h = new SimpleDateFormat("yyyy-MM-dd");
            //今天的日期
            String toDate = format_h.format(new Date());
            //相恋的日期
            String lian = "2022-03-28";
            //两个日期相差的天数
            int cha = DateUtils.getDayByTwoDay(toDate, lian);
            String todayDate = format.format(new Date());

            //根据阳历计算农历
            Calendar today = Calendar.getInstance();
            String week = DateUtils.getDaysByWeekChina(toDate);
            today.setTime(DateUtils.chineseDateFormat.parse(todayDate));
            DateUtils lunar = new DateUtils(today);
            String nongli = lunar.toString();
            nongli = nongli.substring(nongli.indexOf("年") + 1);
            StringBuilder sb = new StringBuilder();
            sb.append("亲爱的老婆~早\n")
                    .append("充满希望的一天又开始了，今天也要一直开心，不能生我气气~")
                    .append("\n今天是：")
                    .append(todayDate)
                    .append("，星期")
                    .append(week)
                    .append("，农历")
                    .append(nongli)
                    .append("\n")
                    .append("是我们相爱的第：")
                    .append(cha)
                    .append("天")
                    .append("\n")

            ;
            JSONObject tianqiObject = TianXingApiUtil.getWeather(tx_key);
            sb.append("目前济南天气：")
                    .append(tianqiObject.getString("weather"))
                    .append("\n")
                    .append("当前气温：")
                    .append(tianqiObject.getString("real"))
                    .append("\n")
                    .append("今天最高温度：")
                    .append(tianqiObject.getString("highest"))
                    .append("\n")
                    .append("最低温度：")
                    .append(tianqiObject.getString("lowest"))
                    .append("\n")
                    .append("风向：")
                    .append(tianqiObject.getString("wind"))
                    .append("\n")
                    .append("空气质量：")
                    .append(tianqiObject.getString("quality"))
                    .append("\n")
                    .append("空气质量指数：")
                    .append(tianqiObject.getString("aqi"))
                    .append("\n")
                    .append("小提示：")
                    .append(tianqiObject.getString("tips"));

            //土味情话
            sb.append("\n")
                    .append("爱你一日言：")
                    .append(TianXingApiUtil.getLoveWords(tx_key))
                    .append("\n【早安寄语】")
                    .append(goodMorning(tx_key));
            weiZhiMiShuVO.setContent(sb.toString());



            for (String str : users) {
                JSONObject object = new JSONObject();
                object.put("apiKey", wei_mi_shu_key);
                //好友昵称
                object.put("name", str);
                //好友备注
                object.put("alias", str);
                object.put("message", weiZhiMiShuVO);
                String body = HttpUtil.createPost(url)
                        .body(JSON.toJSONString(object))
                        .execute()
                        .body();
                System.out.println("传递的参数是：" + JSON.toJSONString(object));
                System.out.println("发送成功了吗?" + body);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    /**
     * 每日一句早安寄语
     */
    @Override
    public String goodMorning(String tx_key){
        //调用每日简报的接口
        return TianXingApiUtil.getGoodMorning(tx_key);
    }

    /**
     * 获取每日IT资讯新闻，添加到文章里面
     * @param
     * @return
     */
    @Override
    public ResponseResult getDaysITNews() {
        //it咨询
        //String path = "it/index";
        //国际新闻
        String path = "world/index";

        //从缓存中获取微信群名
        Object redisObject = redisService.getCacheObject("wechat-webconfig");
        //天行数据的key
        String tx_key = "";
        if(redisObject!=null){
            //缓存中有数据
            JSONObject jsonObject = (JSONObject) redisObject;
            //天行数据的key
            tx_key = jsonObject.getString("txkey");
        }

        //调用每日简报的接口
        String body = HttpUtil
                .createGet(TIAN_XING_API + path + "?key=" + tx_key+"&num=20")
                .execute()
                .body();
        JSONObject jsonObjectResult = JSON.parseObject(body);
        Integer code = jsonObjectResult.getInteger("code");
        if(code!=200){
            log.error("请求每日it新闻的接口出错，出错信息："+body);
            return ResponseResult.error();
        }
        log.error("请求每日it新闻的接口成功："+body);
        JSONObject resultObject = jsonObjectResult.getJSONObject("result");
        //获取新闻列表
        JSONArray contentList = resultObject.getJSONArray("newslist");
        //获取文章的封面信息
       /* String strResult = restTemplate.getForObject(IMG_URL_API_BT, String.class);
        JSONObject jsonObject = JSON.parseObject(strResult);
        Object imgUrl = jsonObject.get("imgurl");*/
        //从七牛云中生成随机数
        String imgUrl = randomImgByQiNiuYun().getData().toString();
        //将新闻列表封装成markdown文章
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String todayDate = simpleDateFormat.format(new Date());
        String titleContent = "# "+todayDate+"国际新闻简要<br/>";
        StringBuilder stringBuilder = new StringBuilder(titleContent);
        //发送到微信群里面的信息
        JSONObject contentObject = new JSONObject();
        contentObject.put("todayDate",todayDate);
        JSONArray array = new JSONArray();
        //遍历接口返回来的json数据
        contentList.forEach(item->{
            JSONObject arrayObject = new JSONObject();
            JSONObject itemObject = (JSONObject)item;
            stringBuilder.append("⏱️");
            stringBuilder.append(itemObject.getString("ctime"));
            stringBuilder.append("<br/>");
            stringBuilder.append("### ");
            stringBuilder.append("🏷️");
            stringBuilder.append(itemObject.getString("title"));
            stringBuilder.append("<br/>");
            stringBuilder.append("📃");
            //描述（此处如果用的是国际新闻的话，需要先注释掉，如果不是国际新闻，是IT的话，需要打开注释）
//            String descriptionStr = itemObject.getString("description");
//            String description = descriptionStr.substring(0, descriptionStr.length() - 6);
//            stringBuilder.append(description);
            String url =itemObject.getString("url");

            stringBuilder.append("<a href='"+url+"' target='_black'>阅读更多</a>");
            //stringBuilder.append("<a href='").append(url).append("' target='_black'>阅读更多</a>");
            stringBuilder.append("<br/>");
            stringBuilder.append("<br/>");
            stringBuilder.append("---");
            stringBuilder.append("<br/>");
            //标题
            arrayObject.put("title",itemObject.getString("title"));
            //内容
           // arrayObject.put("description",description);
            //时间
            arrayObject.put("ctime",itemObject.getString("ctime"));
            array.add(arrayObject);
        });
        contentObject.put("list",array);
        stringBuilder.append("(本文所有数据均来自天行数据api，如有侵权，联系即删~)");
        //将拿到的内容放在Markdown中
        String newContent = stringBuilder.toString();
        MutableDataSet options = new MutableDataSet();
        String markdown = FlexmarkHtmlConverter
                .builder(options)
                .build()
                .convert(newContent)
                .replace("lang-java","java");
        //构建文章的实体
        BlogArticle entity = BlogArticle.builder()
                .userId(7L)
                .contentMd(markdown)
                .categoryId(DAYYS_IT_NEWS)
                .isOriginal(YesOrNoEnum.NO.getCode())
                //转载地址
                .originalUrl("https://www.tianapi.com/")
                .isPublish(1)
                .keywords("IT资讯,穆雄雄,新闻简报")
                .title(todayDate+"IT资讯新闻简要")
                .avatar(imgUrl)
                .content(newContent)
                .build();
        baseMapper.insert(entity);
        //添加标签
        tagsMapper.saveArticleTags(entity.getId(),new ArrayList<Long>() {{add(63L);}});
        log.info("每日新闻添加到文章成功："+ JSON.toJSONString(entity));
        contentObject.put("aid",entity.getId());
        //调用推送到微信的方法
        sendWechatITNews(contentObject);
        return ResponseResult.success("发送成功");
    }


    //    ----------web端方法开始-------
    /**
     *  获取文章列表
     * @return
     */
    @Override
    public ResponseResult listWebArticle(Integer pageIndex, Integer pageSize) {
        Page<Object> page = new Page<Object> ();
        page.setCurrent(pageIndex);
        page.setSize(pageSize);
        Page<ArticlePreviewVO> articlePreviewDTOPage =
                baseMapper.selectPreviewPage(page,
                PUBLISH.code,null,null);
        articlePreviewDTOPage.getRecords().forEach(item -> item.setTagVOList(tagsMapper.findByArticleIdToTags(item.getId())));
        return ResponseResult.success(articlePreviewDTOPage);
    }

    /**
     *  获取文章详情
     * @return
     */
    @Override
    public ResponseResult webArticleInfo(Integer id) {
        ArticleInfoVO blogArticle = baseMapper.selectPrimaryKeyById(id);

        //文章阅读量 在原来的基础上，加+
        Integer oldClicks = blogArticle.getQuantity();
        //实时更新文章阅读量
        BlogArticle blogA = new BlogArticle();
        blogA.setQuantity(oldClicks+1);
        blogA.setId(Long.valueOf(id));
        baseMapper.updateById(blogA);
        //回去最新的点击量
        blogArticle.setQuantity(blogA.getQuantity());
        //标签
        List<TagVO> tags = tagsMapper.findByArticleIdToTags(blogArticle.getId());
        blogArticle.setTagList(tags);
        //分类
        Category category = categoryMapper.selectOne(new LambdaQueryWrapper<Category>().select(Category::getId,Category::getName)
        .eq(Category::getId,blogArticle.getCategoryId()));
        blogArticle.setCategory(category);
        //评论
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<Comment>()
                .eq(SqlConf.ARTICLE_ID, blogArticle.getId()).orderByDesc(SqlConf.CREATE_TIME);
        List<Comment> list = commentMapper.selectList(queryWrapper);
        blogArticle.setComments(list);

        //最新文章
        List<LatestArticleVO> blogArticles = baseMapper.getNewArticles(id, PUBLISH.code);
        blogArticle.setNewestArticleList(blogArticles);

        // 查询上一篇下一篇文章
        LatestArticleVO lastArticle = baseMapper.getNextOrLastArticle(id,0, PUBLISH.code);
        blogArticle.setLastArticle(lastArticle);
        LatestArticleVO nextArticle = baseMapper.getNextOrLastArticle(id,1, PUBLISH.code);
        blogArticle.setNextArticle(nextArticle);

        //相关推荐
        List<LatestArticleVO> recommendArticleList = baseMapper.listRecommendArticles(id);
        blogArticle.setRecommendArticleList(recommendArticleList);

        // 封装点赞量和浏览量
        //blogArticle.setLikeCount((Integer) redisService.hGet(RedisConstants.ARTICLE_LIKE_COUNT, blogArticle.getId().toString()));



        //校验私密文章是否已经进行过验证
        if(blogArticle.getIsSecret().equals(YesOrNoEnum.YES.getCode())){
            List<Object> cacheList = redisService.getCacheList(RedisConstants.CHECK_CODE_IP);
            String ip = IpUtils.getIp(request);
            if (cacheList.contains(ip)) {
                blogArticle.setIsSecret(YesOrNoEnum.NO.getCode());
            }
        }

        //增加文章阅读量
        threadPoolTaskExecutor.execute(() -> this.incr(id.longValue(),ARTICLE_READING));
        return ResponseResult.success(blogArticle);
    }

    /**
     *  获取分类or标签文章
     * @return
     */
    @Override
    public ResponseResult condition(Long categoryId, Long tagId, Integer pageSize) {
        Map<String,Object> result = new HashMap<>();
        Page<ArticlePreviewVO>  blogArticlePage = baseMapper.selectPreviewPage(new Page<>(PageUtils.getPageNo(),pageSize),PUBLISH.getCode(),categoryId,tagId);
        blogArticlePage.getRecords().forEach(item -> {
            List<TagVO> tagList = tagsMapper.findByArticleIdToTags(item.getId());
            item.setTagVOList(tagList);
        });
        String name;
        if (categoryId != null){
            name = categoryMapper.selectById(categoryId).getName();
        }else {
            name = tagsMapper.selectById(tagId).getName();

            threadPoolTaskExecutor.execute(() ->this.incr(tagId,TAG_CLICK_VOLUME));
        }
        result.put(SqlConf.NAME,name);
        result.put(RECORDS,blogArticlePage.getRecords());
        return ResponseResult.success(result);
    }

    /**
     *  获取归档
     * @return
     */
    @Override
    public ResponseResult archive() {
        Page<ArticlePreviewVO> articlePage = baseMapper.selectArchivePage(new Page<>(PageUtils.getPageNo(), PageUtils.getPageSize()),PUBLISH.code);
        return ResponseResult.success(articlePage);
    }

    /**
     *  搜索文章
     * @return
     */
    @Override
    public ResponseResult searchArticle(String keywords) {
        Assert.isTrue(StringUtils.isNotBlank(keywords), PARAMS_ILLEGAL.getDesc());
        //获取搜索模式（es搜索或mysql搜索）
        SystemConfig systemConfig = systemConfigService.getCustomizeOne();
        String strategy = SearchModelEnum.getStrategy(systemConfig.getSearchModel());
        //搜索逻辑
        List<ArticleSearchVO> articleSearchVOS = searchStrategyContext.executeSearchStrategy(strategy, keywords);
        return ResponseResult.success(articleSearchVOS);
    }

    /**
     * 文章点赞
     * @param articleId
     * @return
     */
    @Override
    public ResponseResult articleLike(Integer articleId) {
        // 判断是否点赞
        // 未点赞则增加文章id
        // 文章点赞量+1
        //redisService.hIncr(ARTICLE_LIKE_COUNT, articleId.toString(), 1L);
        //给数据库中更新点赞数量
        BlogArticle blogArticle = baseMapper.selectById(articleId);
        Integer likeCount = blogArticle.getLikeCount()==null?0:blogArticle.getLikeCount();
        blogArticle.setLikeCount(likeCount+1);
        baseMapper.updateById(blogArticle);
        /*String articleLikeKey = ARTICLE_USER_LIKE + StpUtil.getLoginId();
        if (redisService.sIsMember(articleLikeKey, articleId)) {
            // 点过赞则删除文章id
            redisService.sRemove(articleLikeKey, articleId);
            // 文章点赞量-1
            redisService.hDecr(ARTICLE_LIKE_COUNT, articleId.toString(), 1L);
        } else {
            // 未点赞则增加文章id
            redisService.sAdd(articleLikeKey, articleId);
            // 文章点赞量+1
            redisService.hIncr(ARTICLE_LIKE_COUNT, articleId.toString(), 1L);
        }*/
        return ResponseResult.success();
    }

    /**
     * @Description 获取每日新闻，生成图片
     * @Author 穆雄雄
     * @Date:2023/3/13 下午 10:50
     * 博客：https://blog.csdn.net/qq_34137397
     * 个人站：https://www.穆雄雄.com
     * 个人站：https://www.muxiongxiong.cn
     * 个人站：https://88688.team
     * @Param []
     * @return
     **/
    @Override
    public ResponseResult getDaysNewsConvertImage() {
        String path = "bulletin/index";
        //从缓存中获取微信群名
        Object redisObject = redisService.getCacheObject("wechat-webconfig");
        //天行数据的key
        String tx_key = "";
        if(redisObject!=null){
            //缓存中有数据
            JSONObject jsonObject = (JSONObject) redisObject;
            //天行数据的key
            tx_key = jsonObject.getString("txkey");
        }
        //调用每日简报的接口
       /* String body = HttpUtil
                .createGet(TIAN_XING_API + path + "?key=" + tx_key)
                .execute()
                .body();*/
         String body = "{\n" +
                "  \"code\": 200,\n" +
                "  \"msg\": \"success\",\n" +
                "  \"result\": {\n" +
                "    \"list\": [\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 11:32:03\",\n" +
                "        \"title\": \"上海全面推广人工智能精准医学检验 AI+医疗造福患者\",\n" +
                "        \"digest\": \"中国信息通信研究院院长余晓晖指出，发展智能医疗应进一步完善技术创新体系，建设一批面向行业的创新中心、重点实验室等创新载体，打造合作机制。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 10:35:07\",\n" +
                "        \"title\": \"国务院联防联控机制综合组：部署落实新十条防控措施 加快推进医疗资源准备工作\",\n" +
                "        \"digest\": \"会议指出，随着新冠病毒变异和全球疫情变化，以习近平同志为核心的党中央坚持走小步不停步，先后审议出台二十条、新十条措施，推动我国疫情防控进入新阶段。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 09:56:09\",\n" +
                "        \"title\": \"降阶，缩短时间！欧洲心脏病学会老年抗栓共识\",\n" +
                "        \"digest\": \"共识指出，对于老年人来说，选择最佳抗栓治疗方案虽然具有挑战性，但可根据个体特征和多种治疗方案而制定。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 09:21:54\",\n" +
                "        \"title\": \"国家卫健委：昨日新增本土3034+10551| 全国疫情最新消息（2022.12.10）\",\n" +
                "        \"digest\": \"31个省（自治区、直辖市）和新疆生产建设兵团报告新增无症状感染者10729例，其中境外输入178例。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 08:54:26\",\n" +
                "        \"title\": \"广东新增本土确诊病例1115例 新增本土无症状感染者1819例\",\n" +
                "        \"digest\": \"12月9日0-24时，广东省新增本土确诊病例993例，新增本土无症状感染者1819例，另有122例本土无症状感染者转确诊病例。（广东省卫健委网站）\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-10 08:50:46\",\n" +
                "        \"title\": \"12月9日北京新增924例本土确诊病例和1308例无症状感染者\",\n" +
                "        \"digest\": \"12月9日0时至24时，北京新增924例本土确诊病例和1308例无症状感染者(含9例无症状感染者转确诊病例)，无新增疑似病例。（北京市卫生健康委员会）\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 22:53:38\",\n" +
                "        \"title\": \"钟南山：新冠产生的症状会慢慢消失，我们不叫它后遗症\",\n" +
                "        \"digest\": \"钟南山：“医学上对于后遗症有严格的定义，指的是疾病造成的损害终身存在。一些新冠产生的症状会慢慢消失，我们不叫它后遗症。我目前还没看到特别明显的对器官引起长期功能不全的案例。”\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 22:24:27\",\n" +
                "        \"title\": \"用新冠病毒治疗癌症？研究发现新冠刺突蛋白能抑制肺癌发展\",\n" +
                "        \"digest\": \"研究结果突出了重组SARS-CoV-2刺突S1蛋白晚期肺癌患者的新治疗途径。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 21:31:47\",\n" +
                "        \"title\": \"所有医疗机构都要接诊阳性患者！院感防控该怎么做？\",\n" +
                "        \"digest\": \"无论是从卫生经济学的角度，还是从医务人员疲倦心理的角度来说，防控的要求必然会放松。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 20:48:11\",\n" +
                "        \"title\": \"我国重症救治能力如何？全国重症床位近每10万人10张\",\n" +
                "        \"digest\": \"我国重症救治能力如何？国家卫健委医政司司长焦雅辉回应：目前，全国重症医学床位总数是13.81万张，其中三级医疗机构的重症医学床位是10.65万张，重症医学床位接近十万人十张的水平。重症医学的医师总数是8.05万人，还有可转换ICU的储备的医师有10.6万人。另外，重症专业的护士是22万人，可以转换ICU的护士是17.77万人。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 20:21:10\",\n" +
                "        \"title\": \"如何应对可能出现的感染高峰？陈尔真：门急诊做好“三分”管理\",\n" +
                "        \"digest\": \"连日来，国家和地方持续优化新冠防控措施，随着人员交流增多，人群感染风险可能增加。那么，各大医院准备情况如何？当前形势下，大众又该如何合理就医？\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 19:49:33\",\n" +
                "        \"title\": \"村室每月1000元！一地发布标准\",\n" +
                "        \"digest\": \"切实提高乡村医生收入，保障乡村医生待遇。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 19:47:53\",\n" +
                "        \"title\": \"网传海宁某医院医生涉及买卖器官， 当地辟谣\",\n" +
                "        \"digest\": \"网传海宁市某医院医生涉及人体器官买卖。经核实，海宁市人民医院肾内科主任金雯佳涉嫌严重违法，主动投案，目前正在接受海宁市监委监察调查，不存在买卖器官的情况。请广大网友切勿轻信、转发、传播谣言。（海宁新闻网）\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 18:53:50\",\n" +
                "        \"title\": \"实行学术造假“一票否决制”！四川省深化卫生专业技术人员职称制度改革实施方案\",\n" +
                "        \"digest\": \"对于临床医师，将门诊工作时间、收治患者数量、手术数量等作为申报条件。\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"mtime\": \"2022-12-09 17:39:35\",\n" +
                "        \"title\": \"首届上海合作组织国际和平妇幼健康发展论坛在上海举办\",\n" +
                "        \"digest\": \"9日，首届上海合作组织国际和平妇幼健康发展论坛举行，以“交流、互鉴、合作、发展”为主题，围绕“儿童优先、母亲安全”的国际共识，推进上合组织各方在妇幼健康与儿童早期发展领域深化合作。开幕式上，中方发布《中方关于促进上海合作组织妇幼健康合作的倡议（上海）》，提出开展妇幼健康治理策略互鉴、加强妇幼健康医疗技术交流、开展妇女儿童重大健康问题研究合作、搭建妇幼健康产业联盟、建立妇幼健康帮扶基金等五项倡议。\"\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}";

        JSONObject jsonObjectResult = JSON.parseObject(body);
        Integer code = jsonObjectResult.getInteger("code");
        if(code!=200){
            log.error("请求每日新闻的接口出错，出错信息："+body);
            return ResponseResult.error();
        }
        log.error("请求每日新闻的接口成功："+body);
        JSONObject resultObject = jsonObjectResult.getJSONObject("result");
        //获取新闻列表
        JSONArray contentList =  resultObject.getJSONArray("list");
        JSONArray contentListArray = new JSONArray();
       for(int i  = 0;i<10;i++){
           contentListArray.add(contentList.get(i));
       }
        return ResponseResult.success(contentListArray);
    }

    /**
     * 获取今天的提起
     * @return
     */
    @Override
    public ResponseResult getTodaysInfo() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String todayDate = simpleDateFormat.format(new Date());
        //根据阳历计算农历
        Calendar today = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        // 因为按中国礼拜一作为第一天所以这里减1
        String week = "";
        JSONObject object = new JSONObject();
        try {
            week = DateUtils.getDaysByWeekChina(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            today.setTime(DateUtils.chineseDateFormat.parse(todayDate));
            DateUtils lunar = new DateUtils(today);
            String nongli = lunar.toString();
            nongli = nongli.substring(nongli.indexOf("年") + 1);
            object.put("week", week);
            object.put("nongli", nongli);
            object.put("todayDate", todayDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResponseResult.success(object);
    }

    /**
     *  校验文章验证码(验证码通过关注公众号获取)
     * @return
     */
    @Override
    public ResponseResult checkSecret(String code) {
        //校验验证码
        String key = RedisConstants.WECHAT_CODE + code;
        Object redisCode = redisService.getCacheObject(key);
        Assert.isTrue(redisCode != null, ERROR_EXCEPTION_MOBILE_CODE.getDesc());

        //将ip存在redis 有效期一天，当天无需再进行验证码校验
        List<Object> cacheList = redisService.getCacheList(CHECK_CODE_IP);
        if (cacheList.isEmpty()) {
            cacheList = new ArrayList<>();
        }
        cacheList.add(IpUtils.getIp(request));
        redisService.setCacheList(CHECK_CODE_IP,cacheList);
        //通过删除验证码
        redisService.deleteObject(key);
        return ResponseResult.success("验证成功");
    }

    //    -----自定义方法开始-------
    /**
     *  增加文字阅读量或标签点击量
     * @return
     */
    public void incr(Long id,String key) {
        Map<String, Object> map = redisService.getCacheMap(key);
        Integer value = (Integer) map.get(id.toString());
        // 如果key存在就直接加一
        if (value != null) {
            map.put(id.toString(),value+1);
        }else {
            map.put(id.toString(),1);
        }
        redisService.setCacheMap(key,map);
    }

    /**
     * 删除文章后的一些同步删除
     * @param ids
     */
    private void deleteAfter(List<Long> ids){
        tagsMapper.deleteByArticleIds(ids);
        threadPoolTaskExecutor.execute(()->this.deleteEsData(ids));
    }

    /**
     * 删除es索引库的数据
     * @param ids
     */
    private void deleteEsData(List<Long> ids){
        ids.forEach(elasticsearchUtil::delete);
    }

    /**
     * 将数据库不存在的标签新增
     * @param article
     * @return
     */
    private List<Long> getTagsList(ArticleDTO article) {
        List<Long> tagList = new ArrayList<>();
        article.getTags().forEach(item ->{
            Tags tags = tagsMapper.selectOne(new QueryWrapper<Tags>().eq(SqlConf.NAME, item));
            if (tags == null){
                tags = Tags.builder().name(item).sort(0).build();
                tagsMapper.insert(tags);
            }
            tagList.add(tags.getId());
        });
        return tagList;
    }

    /**
     * 如果分类不存在则新增
     * @param categoryName
     * @return
     */
    private Long savaCategory(String categoryName) {
        Category category = categoryMapper.selectOne(new QueryWrapper<Category>().eq(SqlConf.NAME, categoryName));
        if (category == null){
            category = Category.builder().name(categoryName).sort(0).build();
            categoryMapper.insert(category);

        }
        return category.getId();
    }


}
